#include "../include/soundplayer.h"
#include "../include/RIFF.h"
#include <unistd.h>

environment_t env;

void analyze_wav(FILE* input){
	//preforms analysis of file
	RIFF header;
	char wav[5];

	fread(wav, 1, 4, input); //read in the magic
	wav[4] = 0; //nul terminate
	if(cmp(wav, "RIFF") == 0) {
		//assume header exists and analyze the data
		rewind(input);
		fread(&header, sizeof(header), 1, input); //populate struct

		//alter appropriate values
		if(FLAGUNSET(SP_OVERRIDE_CHANNEL)) env->channels = header.channels;
		if(FLAGUNSET(SP_OVERRIDE_HERTZ)) env->rate = header.hz;
		pcm_output_configure();
	}
}

void play_wav(FILE* input){
	//make buffer
	//buffer size is 1024 samples

	char wav[pcm_output_frames_to_bytes(1024)];
	int status;

	analyze_wav(input);

	if (env->status != SP_IDLE) goto END;
	env->status = SP_PLAY;

	do {
		//handle all statuses in 3 lines
		if (env->status > SP_PLAY) {
			while (env->status == SP_PAUSE) sleep(1);
			if (env->status > SP_PAUSE) goto CLEANUP;
		}
		status = fread(wav, 1, sizeof(wav), input);
		pcm_output_write(wav,  pcm_output_bytes_to_frames(status) );
		if (env->progress != NULL) env->progress(ftell(input), env->size);
	}
	while (env->status < SP_STOP && status > 0);

	CLEANUP:
	env->status = SP_IDLE;

	END:
		;
}
